package com.a918.config;

import com.a918.entity.Permission;
import com.a918.entity.Role;
import com.a918.entity.User;
import com.a918.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //new一个授权信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        //此处把当前subject对应的所有角色信息交给shiro，调用hasRole的时候就根据这些role信息判断
//        authorizationInfo.addRoles(roleNames);
        //此处把当前subject对应的权限信息交给shiro，当调用hasPermission的时候就会根据这些信息判断
        List<String> permissionurl = userService.findPermissions(user.getId());
//        permissionurl.add("waiting");

        if(permissionurl.size()==0){
            permissionurl.add("waiting");
        }
        authorizationInfo.addStringPermissions(permissionurl);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名称
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//        SysUser sysUser = sysUserService.findByUserName(token.getUsername());
//        String username = (String) token.getPrincipal();
        User user = userService.getUserByUsername(token.getUsername());
        // 用户名不存在抛出异常
        if (user == null) throw new UnknownAccountException();
        String pwd = user.getPassword();
        return new SimpleAuthenticationInfo(user, pwd, getName());
    }
}

